#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>

#define LEFT  30000000
#define RIGHT 30000200
#define THREADS (RIGHT - LEFT + 1)

static void* check_prime(void* arg) {
    const int* p = arg;
    int i = *p;

    for(int j = 2; j < i / 2; j++) {
        if(i % j == 0) {
            pthread_exit(arg);
        }
    }    
    printf("%d is a prime number\n", i);
    pthread_exit(arg);    
}

int main() {
    pthread_t threads[THREADS];

    int i;
    for(i = LEFT; i < RIGHT + 1; i++) {
        int *p = malloc(sizeof(int));
        *p = i;
        // 传给 pthread_create 指针如果是一个变量，不能使用指向栈内存的指针
        int err = pthread_create(threads + i - LEFT, NULL, check_prime, p);

        if(err) {
            fprintf(stderr, "pthread_create(): %s\n", strerror(err));
            exit(1);
        }
    }

    for(int i = 0; i < THREADS; i++) {
        void* ptr;
        pthread_join(threads[i], &ptr);
        free(ptr);
    }
}

